const DB = require('../core/DB')
const {
    Op
} = require('sequelize')

DB.article.hasMany(DB.tag_article)
DB.article.hasOne(DB.article_info)
DB.tag_article.belongsTo(DB.article)
DB.tag_article.belongsTo(DB.tag)


class ArticleController {
    /* --------------------------------------------------------------------ok 前台搜索文章 -------------------------------*/
    async searchArticle(ctx) {
        // 参数
        let {
            key = '' // 关键词
        } = ctx.request.query

        const {
            count,
            rows
        } = await DB.article.findAndCountAll({
            order: [
                ['sort', 'DESC'],
                ['id', 'DESC']
            ],
            where: {
                title: {
                    [Op.like]: `%${key}%`
                }
            }
        })

        for (let article of rows) {
            let articleId = article.get('id')
            let t_a = await DB.tag_article.findAll({
                where: {
                    articleId
                },
                include: DB.tag
            })

            let arr = []
            for (let v of t_a) {
                arr.push(v.get('tag'))
            }

            article.dataValues.tags = arr
        }

        const data = {
            rows,
            meta: {
                key,
                count, // 条目总数
            }
        }
        global.Response.success(ctx, undefined, data)
    }


    /* --------------------------------------------------------------------ok 获取文章点赞和浏览 -------------------------------*/
    async getArticleInfo(ctx) {
        let {
            id
        } = ctx.query
        const data = await DB.article_info.findByPk(id)
        global.Response.success(ctx, undefined, data)

    }
    /* -------------------------------------------------------------------- ok 文章点赞和浏览 -------------------------------*/
    async updateArticleInfo(ctx) {
        let {
            like,
            browse,
            articleId
        } = ctx.request.body

        try {
            if (like) {
                await DB.article_info.increment({
                    like: 1
                }, {
                    where: {
                        articleId
                    }
                })
            } else if (browse) {
                await DB.article_info.increment({
                    browse: 1
                }, {
                    where: {
                        articleId
                    }
                })
            }
            global.Response.success(ctx, undefined, DB.article_info)
        } catch (err) {
            global.Response.error(ctx, err)
        }

    }

    /* -------------------------------------------------------------------- ok 获取时间轴 -------------------------------*/
    async getTimeline(ctx) {
        const articles = await DB.article.findAll({
            where: {
                status: 1
            },
            order: [
                ['createdAt', 'DESC']
            ],
        })

        // 声明空数组 存储间隔年份
        let timeTineArr = []

        if (articles.length == 0) {
            global.Response.success(ctx, '暂无文章', timeTineArr)
            return false;
        }

        // 获取首尾巴年份 依次获取各年份
        const endYear = global.Moment(articles[0].createdAt)
        const startYear = global.Moment(articles[articles.length - 1].createdAt)

        while (startYear <= endYear) { // 要确保 startYear 小于 endYear !!
            timeTineArr.push({
                currentYear: startYear.format('YYYY'),
                currentArticles: []
            })
            startYear.add(1, 'years')
        }

        articles.forEach(article => {
            // 对每年份遍历
            timeTineArr.forEach(time => {
                if (global.Moment(article.createdAt).format('YYYY') == time.currentYear) {
                    time.currentArticles.push(article)
                }
            })
        })

        timeTineArr.reverse() // 年份反转，如果前面已倒序 则不用反转

        global.Response.success(ctx, undefined, timeTineArr)
    }



    /* ------------------------------------------------------------------- ok 前台获取所有文章 -------------------------------*/
    async listArticle(ctx) {
        // 参数
        let {
            page = 1, size = 10, key = '' // 关键词
        } = ctx.query

        page = Number(page)
        size = Number(size)

        const {
            count,
            rows
        } = await DB.article.findAndCountAll({
            offset: (page - 1) * size,
            limit: size,
            order: [
                ['sort', 'DESC'],// 排序
                ['id', 'DESC']
            ],
            where: {
                status: 1 // 显示状态为可见
            }
        })

        for (let article of rows) {
            let articleId = article.get('id')
            let t_a = await DB.tag_article.findAll({
                where: {
                    articleId
                },
                include: DB.tag
            })

            let arr = []
            for (let v of t_a) {
                arr.push(v.get('tag'))
            }

            article.dataValues.tags = arr
        }

        const data = {
            rows,
            meta: {
                key,
                size, // 每页条目
                count: count, // 条目总数
                page: page, // 当前页数
                total: Math.ceil(count / size), // 总页数
            }
        }
        global.Response.success(ctx, undefined, data)
    }

    /* -------------------------------------------------------------------- ok 获取指定文章详情 -------------------------------*/
    async getArticleDetail(ctx) {
        let {id:articleId} = ctx.query
        const article = await DB.article.findByPk(articleId)

        if (!article) {
            global.Response.null(ctx)
            return
        }

        // 加载标签
        let t_a = await DB.tag_article.findAll({
            where: {
                articleId
            },
            include: DB.tag
        })

        let arr = []
        for (let v of t_a) {
            arr.push(v.get('tag'))
        }

        article.dataValues.tags = arr

        global.Response.success(ctx, undefined, article)
    }




}

module.exports = new ArticleController